import React, { useRef, useState,useImperativeHandle } from 'react';


// 使用 React.forwardRef 配合useImperativeHanlde使用
// 使用 React.forwardRef() 函数包裹了 函数式子组件；
// React.forwardRef(props,ref) 有2个参数 一个是 props 一个是父组件传过来得ref对象；
export const Children = React.forwardRef((_,ref) => {
    

    const [count, setCount] = useState(0);
    const changeFun = (setp: number) => {
        setCount((old) => {
            return old = old + setp
        })
    }

    // 显示得提供要向外 暴露得成员；像外导出
    useImperativeHandle(ref,()=>({
        name:"lkx"
    }))

    return (
        <>
            <div>
                <h2>子组件</h2>
                <p>数字：{count}</p>
                <button onClick={() => {
                    changeFun(1)
                }}>+1</button>
                <button onClick={() => {
                    changeFun(-1)
                }}>-1</button>
            </div>
        </>
    )
})

export const Father: React.FC = () => {
    const childRef = useRef();
    const showRef = ()=>{
        console.log(childRef.current);
    }
    return (
        <>
            <h1>父亲元素</h1>
            <button onClick={showRef}>showRef</button>
            {/* useRef 无法使用ref直接引用函数式子组件 */}
            {/* Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? */}
            <Children ref={childRef}></Children>
            
        </>
    )
}